package com.gy.ai.agent.listener;

import com.gy.ai.agent.Platform;
import com.gy.ai.agent.client.BaseReqClient;
import com.gy.ai.agent.core.BaseResponse;
import com.gy.ai.agent.core.ReqContext;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;

/**
 * @author LGY
 * Create by 2025/6/16 14:37
 */
public class BaseReqClientListener implements ReqClientListener {

    private final StreamRespListener streamResponseListener;
    private final ReqContext context;


    public BaseReqClientListener(Platform platform, StreamRespListener streamResponseListener, BaseReqClient reqClient, ReqContext context) {
        this.streamResponseListener = streamResponseListener;
        this.context = new ReqContext(platform, reqClient);
    }

    @Override
    public void onStart(BaseReqClient client) {
        streamResponseListener.onStart(context);
    }

    @Override
    public void onMessage(BaseReqClient client, String response) {
        if (StringUtils.isBlank(response) || Objects.equals(response.trim(), "[DONE]")) {
            return;
        }
        try {
            streamResponseListener.onMessage(context, new BaseResponse(response));
        } catch (Exception e) {
            streamResponseListener.onFailure(context, e);
        }
    }

    @Override
    public void onStop(BaseReqClient client) {
        streamResponseListener.onStop(context);
    }

    @Override
    public void onFailure(BaseReqClient client, Throwable throwable) {
        streamResponseListener.onFailure(context, throwable);
    }
}
